<template>
  <div>
    <!-- 卡片视图 -->
    <the-table
      :total="state.total"
      :data="state.tableData"
      :pageInfo="state.pageInfo"
      @clearInput="getData"
      @handleExport="exportExcel"
      @search="querySearch"
      @pageInfoChange="pageInfoChange"
      @handleAdd="state.addDialogVisuble = true"
      @handleImport="state.excelInDialogVisible = true"
      :columns="state.columns"
      :layout="['addBtn', 'search', 'column', 'importBtn', 'exportBtn']"
    >
      <template v-slot:extractbtn>
        <div class="block" style="display: flex;">
          <span style="line-height:32px">所属地查询：</span>
          <regional-league @areaChange="areaSearch" />
        </div>
      </template>
      <el-table-column
        prop="schoolName"
        label="高校名称"
        width="180"
        align="left"
        v-if="state.columns[0].show"
      />
      <el-table-column
        prop="cityInfo"
        label="所属地"
        width="180"
        align="center"
        v-if="state.columns[1].show"
      >
        <template #default="scope">
          <span v-if="scope.row.cityInfo">{{ scope.row.cityInfo.merName }}</span>
          <el-tag v-else type="success">暂无信息</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="level" label="等级" v-if="state.columns[2].show" />
      <el-table-column prop="department" label="直属部门" v-if="state.columns[3].show" />
      <el-table-column prop="schoolId" label="学校代码" v-if="state.columns[4].show" />
      <el-table-column label="操作" width="230px">
        <template #default="scope">
          <el-button
            style="color: #67c23a"
            type="text"
            size="small"
            @click="goFaculty(scope.row.id)"
          >
            <el-icon class="el-input__icon">
              <edit />
            </el-icon>院系管理
          </el-button>
          <el-button
            style="color: #409eff"
            type="text"
            size="small"
            @click="openEditDialog(scope.row)"
          >
            <el-icon class="el-input__icon">
              <edit />
            </el-icon>编辑
          </el-button>
          <el-button
            type="text"
            style="color: #f56c6c"
            size="small"
            @click="deleteById(scope.row.id)"
          >
            <el-icon class="el-input__icon">
              <delete />
            </el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>
    <el-dialog title="添加高校" v-model="state.addDialogVisuble" width="50%" @open="clearAddForm">
      <el-form
        label-position="right"
        label-width="90px"
        :model="state.universityForm"
        ref="formRef"
      >
        <el-form-item label="高校名称:" prop="schoolName">
          <el-input v-model="state.universityForm.schoolName" placeholder="请输入高校名"></el-input>
        </el-form-item>
        <el-form-item label="高校代码:" prop="schoolId">
          <el-input v-model="state.universityForm.schoolId" placeholder="请输入高校代码"></el-input>
        </el-form-item>
        <el-form-item label="地区:" prop="provinceName">
          <regional-league @areaChange="areaChange" />
        </el-form-item>
        <el-form-item label="等级:" prop="level">
          <el-select v-model="state.universityForm.level">
            <el-option label="专科" value="专科"></el-option>
            <el-option label="本科" value="本科"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门:" prop="department">
          <el-input v-model="state.universityForm.department"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.addDialogVisuble = false">取 消</el-button>
          <el-button type="primary" @click="addConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="修改高校信息"
      v-model="state.editDialogVisible"
      width="50%"
      @close="state.isShowArea = false"
    >
      <el-form
        label-position="right"
        label-width="140px"
        :model="state.editForm"
        ref="formRef"
        :rules="state.rules"
      >
        <el-form-item label="高校名称:" prop="schoolName">
          <el-input v-model="state.editForm.schoolName" placeholder="请输入高校名"></el-input>
        </el-form-item>
        <el-form-item label="高校代码:" prop="schoolId">
          <el-input v-model="state.editForm.schoolId" placeholder="请输入高校代码"></el-input>
        </el-form-item>
        <el-form-item label="地区:" prop="provinceName">
          <regional-league
            v-if="state.isShowArea"
            @areaChange="editArea"
            :provinceName="provinceName"
            :cityName="cityName"
          />
        </el-form-item>
        <el-form-item label="等级:" prop="level" class="levelChoose">
          <el-select v-model="state.editForm.level">
            <el-option label="专科" value="专科"></el-option>
            <el-option label="本科" value="本科"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门:" prop="department">
          <el-input v-model="state.editForm.department"></el-input>
        </el-form-item>
      </el-form>
      <template #footer #default="scope">
        <span class="dialog-footer">
          <el-button @click="state.editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 导入excel -->
    <el-dialog title="导入文件" v-model="state.excelInDialogVisible" width="27%" @closed="clearUpload">
      <el-upload
        class="upload-demo"
        drag
        ref="uploadRef"
        :headers="headers"
        :auto-upload="true"
        action="http://112.74.61.241:8081/orgs/univ/batchImportUnivs"
        :before-upload="beforeUpload"
        :multiple="false"
        :on-exceed="handleExceed"
        accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        :limit="1"
        :http-request="uploadExcel"
      >
        <!-- :http-request="uploadExcel" -->
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">
          拖拽文件或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">一次只能上传一个文件</div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="state.excelInDialogVisible = false">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" >
import { defineComponent, reactive, Ref, ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { addLogs } from '#/Home/Home'
import TheTable from "@/components/common/TheTable.vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import RegionalLeague from '@/components/OrganizationManagement/RegionalLeague.vue'
import { getUniversity, addUniversity, updateUniversity, searchUniversityByName, deleteUniversity, exportUniversityExcel, searchUnivByArea, uploadUnivExcel } from '@/api/OrganizationManagement/university'
export default defineComponent({
  components: {
    RegionalLeague,
    TheTable
  },
  setup() {
    const state = reactive({
      queryInfo: '',
      tableData: [],
      pageInfo: {
        isShow: true,
        pageSize: 5,
        pageNum: 1,
        placeholder: "请输入内容",
      },
      total: 0,
      columns: [
        { name: "高校名", show: true },
        { name: "所属地", show: true },
        { name: "等级", show: true },
        { name: "直属部门", show: true },
        { name: "学校代码", show: true },
      ],
      editForm: {
        schoolName: '',
        cityId: '',
        schoolId: '',
        department: '',
        level: '',
      },
      editId: '',    //要修改的目标ID
      isShowArea: true,
      excelInDialogVisible: false,
      addDialogVisuble: false,
      editDialogVisible: false,
      universityForm: {
        schoolName: '',
        cityId: '',
        schoolId: '',
        department: '',
        level: '',
      },
      rules: {
        schoolName: [
          { required: true, message: "请输入高校名称", trigger: "blur" },
        ],
        department: [
          { required: true, message: "请输入直属部门", trigger: "blur" },
        ],
        level: [
          { required: true, message: "请选择高校等级", trigger: "blur" },
        ],
        schoolId: [
          { required: true, message: "请输入高校代码", trigger: "blur" },
        ],
      }

    })
    const headers = {
      "Content-Type": "multipart/form-data",
      Authorization: sessionStorage.getItem("token"),
      userId: window.sessionStorage.getItem('userId'),
    }
    const router = useRouter()
    let uploadRef: any = ref(null)
    const fileExcelList: Ref<Array<any>> = ref([])
    const formRef: any = ref(null);    //表单Dom对象ref
    let provinceName: Ref<string> = ref('')
    let cityName: Ref<string> = ref('')

    const getData = async (): Promise<void> => {
      const res: any = await getUniversity(state.pageInfo.pageNum, state.pageInfo.pageSize)
      if (res.data.ret === 0) {
        state.tableData = res.data.orgs.univ.content
        state.total = res.data.orgs.univ.totalElements
      }
      console.log(res)
    }

    getData()
    const querySearch = async (queryInfo: string): Promise<void> => {
      state.pageInfo.pageNum = 1
      const res: any = await searchUniversityByName(queryInfo, state.pageInfo.pageNum, state.pageInfo.pageSize)
      if (res.data.ret === 0) {
        ElMessage.success('查询成功')
        state.tableData = res.data.orgs.univ.content
        state.total = res.data.orgs.univ.totalElements
      }
    }
    const areaChange = (areaInfo: any, cityInfo: any): void => {
      state.universityForm.cityId = cityInfo.id + ''
    }

    const clearAddForm = (): void => {
      nextTick(() => {
        formRef.value.resetFields()
      })
    }
    const areaSearch = async (areaInfo: any, cityInfo: any): Promise<void> => {
      console.log(cityInfo)
      await searchUnivByArea(cityInfo.id, state.pageInfo.pageNum, state.pageInfo.pageSize).then((res: any) => {
        if (res.data.ret === 0) {
          state.tableData = res.data.orgs.univ.content
          state.total = res.data.orgs.univ.totalElements
          ElMessage.success('查询成功')
          console.log(res)
        }
      })
    }

    //修改地址
    const editArea = (areaInfo: any, cityInfo: any): void => {
      state.editForm.cityId = cityInfo.id
    }

    const exportExcel = async (): Promise<void> => {
      await exportUniversityExcel().then(res => {
        if (res.status === 200) {
          console.log(res)
          let data: any = res.data
          const blob = new Blob([data], {  // res 为后台返回数据
            type: 'application/vnd.ms-excel;charset=utf-8', // 导出数据生成excel的格式设置
          });
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a');
            elink.download = `高校信息.xlsx`;
            elink.style.display = 'none';
            elink.target = '_blank';
            elink.href = window.URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
          }
          ElMessage.success('导出成功')
        }
      })
    }

    const addConfirm = async (): Promise<void> => {
      await addUniversity(state.universityForm).then((res: any) => {
        if (res.data.ret === 0) {
          ElMessage.success(res.data.msg)
          getData()
          state.addDialogVisuble = false
        }
      })
    }

    const pageInfoChange = (type: string, newValue: number): void => {
      type === 'size' ? state.pageInfo.pageSize = newValue : state.pageInfo.pageNum = newValue;
      getData()
    }

    const openEditDialog = (obj: any): void => {
      console.log(obj)
      state.editForm.schoolName = obj.schoolName
      state.editForm.schoolId = obj.schoolId
      state.editForm.level = obj.level
      state.editForm.department = obj.department
      state.editId = obj.id
      state.isShowArea = true
      if (obj.cityInfo) {
        provinceName.value = obj.cityInfo.merName.split(",")[1]
        cityName.value = obj.cityInfo.merName.split(",")[2]
      }
      state.editDialogVisible = true
    }

    const editConfirm = async (): Promise<void> => {
      const res: any = await updateUniversity(state.editId, state.editForm)
      console.log(res)
      if (res.data.ret === 0) {
        ElMessage.success(res.data.msg)
        getData()
        addLogs({
          userId: window.sessionStorage.getItem('userId'),
          behavior: '成功修改了高校信息信息',
        })
        state.editDialogVisible = false
      }
    }


    const deleteById = async (id: string): Promise<void> => {
      const confirmRes = await ElMessageBox.confirm(
        "此操作将永久删除该学校信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err: any) => err);
      if (confirmRes === 'confirm') {
        await deleteUniversity(id).then((res: any) => {
          if (res.data.ret === 0) {
            ElMessage.success('删除成功')
            console.log(res)
            getData()
            addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '成功删除了高校信息信息',
            })
          }
        })
      }
    }

    const beforeUpload = (file: any) => {
      const isText = file.type === 'application/vnd.ms-excel';
      const isTextComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      if (!isText && !isTextComputer) {
        ElMessage.warning('请上传excel格式文件！');
        return
      }
      const fileSize = file.size / 1024 / 1024 < 5
      if (!fileSize) {
        ElMessage.warning('文件大小不能超过5M');
        return
      }
      return (isText || isTextComputer);
    }

    //文件数量超过limit时触发的方法
    const handleExceed = (files, fileList) => {
      console.log(files, fileList)
      ElMessage.warning('当前限制选择 1 个文件，请删除后继续上传');
    }

    const uploadExcel = async (item): Promise<void> => {
      const fileObj = item.file;
      console.log(fileObj)
      const form = new FormData();
      form.append('file', fileObj);
      console.log(form)
      await uploadUnivExcel(form).then((res: any) => {
        if (res.data.ret === 0) {
          ElMessage.success('文件：' + fileObj.name + res.data.msg);
          fileExcelList.value = [];
          getData()
        }
      }).catch(() => {
        // ElMessage.error('文件：' + fileObj.name + '上传失败！');
      }).finally(() => {
        fileExcelList.value = [];
      });
    }

    const clearUpload = () => {
      uploadRef.value.clearFiles()
    }

    //跳转到院系管理
    const goFaculty = (id: string): void => {
      router.push("/OrganizationManagement/Department?id=" + id);
    }
    return {
      state,
      headers,
      querySearch,
      formRef,
      clearAddForm,
      editArea,
      getData,
      editConfirm,
      provinceName,
      cityName,
      beforeUpload,
      uploadExcel,
      areaSearch,
      pageInfoChange,
      exportExcel,
      handleExceed,
      areaChange,
      addConfirm,
      openEditDialog,
      deleteById,
      goFaculty,
      uploadRef,
      clearUpload
    }
  }
})
</script>
<style lang="scss" scoped>
.el-select {
  width: 120px;
}
.el-input {
  width: 80%;
  padding-right: 50px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.el-pagination {
  padding-top: 60px;
}

.block {
  display: flex;
}

:deep(.levelChoose) .el-input__suffix {
  right: 0;
}
</style>
